package com.woniu.springmybatis.action.UserOperateLog;

import com.woniu.springmybatis.entity.User;
import com.woniu.springmybatis.entity.User_operatelog;
import com.woniu.springmybatis.service.User_operatelogService;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerFactory;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;


/**
 * 处理用户操作日志切面类
 */

@Component//组成
@Aspect//
public class LogAspect {

    private static final Logger LOGGER = Logger.getLogger(LogAspect.class);

    @Resource
    private User_operatelogService user_operatelogService;
    //在springmabatis下全部可以添加切点
    @Pointcut("@annotation(com.woniu.springmybatis.action.UserOperateLog.UserOperate)")
      public void controllerAspecta() {
    };


    @AfterReturning(value = "controllerAspecta() && @annotation(annotation)&&args(object,..)",argNames="annotation,object")
    public void interceptorApplogicA(UserOperate annotation,Object object) throws Throwable{

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        User userInfo = (User) session.getAttribute("user");
        User userInfo = (User) request.getSession().getAttribute("user");
        User_operatelog user_operatelog = new User_operatelog();
        //获取操作人用户名id
        user_operatelog.setUser_id(userInfo.getId());
        //获取操作方法
        user_operatelog.setModule_name(annotation.module_name());
        //获取操作内容
        user_operatelog.setOperate_desc(annotation.option());
        //获取ip地址
        user_operatelog.setIp_address(this.getIpAddr(request));
        //获取操作时间
        user_operatelog.setTime(new Date());
        //写入数据库
        user_operatelogService.insertLog(user_operatelog);

    }

    /**
     * 获取ip地址
     */
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;

    }
}